package com.ruoyi.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.channel.domain.TChannelDataConf;
import com.ruoyi.channel.mapper.TChannelDataConfMapper;
import com.ruoyi.channel.service.ITChannelDataConfService;
import com.ruoyi.channelApi.mapper.TChannelPushMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.customer.SentMessage;
import com.ruoyi.customer.domain.TCommentRecord;
import com.ruoyi.customer.domain.TMemoRecord;
import com.ruoyi.customer.mapper.TCommentRecordMapper;
import com.ruoyi.customer.mapper.TMemoRecordMapper;
import com.ruoyi.customer.service.ICustomerService;
import com.ruoyi.system.domain.CommonConfig;
import com.ruoyi.system.domain.vo.LoginTimeVo;
import com.ruoyi.system.mapper.CommonConfigMapper;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;


/**
 * @author suntf
 * @version 1.0
 * @date 2023/8/16 20:50
 */
@Component
@EnableScheduling
public class TaskJobConfig {

    @Autowired
    ICustomerService customerService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    private TMemoRecordMapper memoRecordMapper;
    @Autowired
    private TCommentRecordMapper commentRecordMapper;
    @Autowired
    private TChannelDataConfMapper channelDataConfMapper;
    @Autowired
    private ITChannelDataConfService channelDataConfService;
    @Autowired
    private CommonConfigMapper commonConfigMapper;

    /**
     * 获取在线用户发送到期用户信息
     *
     * @param
     * @return void
     * @author: suntf
     * @date: 2023/8/16 20:51
     */
    //@Scheduled(cron = "0 1 0 * * ?")
    public void updateChannelDisUserId() {
        List<TChannelDataConf> channelDataConfList = channelDataConfMapper.selectList();
        if (CollectionUtils.isEmpty(channelDataConfList)) {
            return;
        }
        System.out.println("进来了");
        List<TChannelDataConf> updateChannelDataList = new ArrayList<>();
        for (TChannelDataConf channelDataConf : channelDataConfList) {
            TChannelDataConf dataConf = new TChannelDataConf();
            dataConf.setId(channelDataConf.getId());
            dataConf.setDisUserId(-1L);
            updateChannelDataList.add(dataConf);
        }
        channelDataConfMapper.updateBatchById(updateChannelDataList);
        updateChannelDataList.forEach(it->{
            channelDataConfService.disUserInfoUpdate(it.getId(), "1");
        });
        System.out.println("更新了");
    }



    /**
     * 获取在线用户发送到期用户信息
     *
     * @param
     * @return void
     * @author: suntf
     * @date: 2023/8/16 20:51
     */
    @Scheduled(cron = "0 0 10,17 * * ?")
    public void sendMsg() {
        customerService.sendStarCustomerToUser();
    }

    /**
     * 晚上22点回收 回收客户
     *
     * @param
     * @return void
     * @author: suntf
     * @date: 2023/8/18 14:25
     */
    @Scheduled(cron = "0 0 22 * * ?")
    public void recoverCustomer() {
        // 回收客户标识 如果 1 回收 0 否
        String flag = sysConfigService.selectConfigByKey(Constants.RECOVER_FLAG);
        if ("1".equals(flag)) {
            // 判断时间信息
            if (checkRecoverTime()) {
                customerService.recoverCustomer();
            }
        }
    }
    private boolean checkRecoverTime() {
        LambdaQueryWrapper<CommonConfig> configWrapper = new LambdaQueryWrapper<>();
        configWrapper.eq(CommonConfig::getType, "recover_time");
        List<CommonConfig> configList = commonConfigMapper.selectList(configWrapper);
        if (CollectionUtils.isEmpty(configList)) {
            return false;
        }
        CommonConfig commonConfigVo = configList.get(0);
        LoginTimeVo loginTimeVo = JsonUtils.parseObject(commonConfigVo.getInfo(), LoginTimeVo.class);
        if (loginTimeVo == null) {
            return false;
        }
        List<String> weekConfig = loginTimeVo.getWeekConfig();
        if (CollectionUtils.isEmpty(weekConfig)) {
            return false;
        }
        // 获取当前日期是周几
        String week = DateUtils.getWeek();
        if (!StringUtils.isNotBlank(week)) {
            return false;
        }
        return weekConfig.contains(week);
    }

    /**
     * 晚上22点半下发 回收客户
     *
     * @param
     * @return void
     * @author: suntf
     * @date: 2023/8/18 14:25
     */
    @Scheduled(cron = "0 30 22 * * ?")
    public void recoverDisCustomer() {
        String flag = sysConfigService.selectConfigByKey(Constants.RECOVER_FLAG);
        String recoverSwitch = sysConfigService.selectConfigByKey(Constants.ROTATE_FLAG_SWITCH);

        if ("1".equals(flag) && "1".equals(recoverSwitch)) {
            String rotateFlag = sysConfigService.selectConfigByKey(Constants.ROTATE_FLAG);
            customerService.recoverDisCustomer(rotateFlag);
        }

    }

    // 待添加任务执行 发送消息 暂定每一分钟执行一次
    @Scheduled(cron = "0 */1 * * * ?")
    public void memoRecord() {
        List<TMemoRecord> tMemoRecords = new ArrayList<>();
        // 备忘录
        String memoFlag = sysConfigService.selectConfigByKey(Constants.MEMO_RECORD);
        if (Objects.equals(memoFlag, "1")) {
            LambdaQueryWrapper<TMemoRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.ne(TMemoRecord::getIsOpen, 1);
            lambdaQueryWrapper.eq(TMemoRecord::getDelFlag, "0");
            String time = DateUtils.parseDateToStr(
                    DateUtils.YYYY_MM_DD_HH_MM, DateUtils.getNowDate());
            //lambdaQueryWrapper.apply("( DATE_FORMAT( notice_time, '%Y-%m-%d %H:%i') = '" + time + "')");
            lambdaQueryWrapper.apply("( notice_time  <= now() )");
            tMemoRecords = memoRecordMapper.selectList(lambdaQueryWrapper);
        }

        List<TCommentRecord> commentRecords = new ArrayList<>();
        // 点评提醒
        String commentFlag = sysConfigService.selectConfigByKey(Constants.COMMENT_RECORD);
        if (Objects.equals(commentFlag, "1")) {
            LambdaQueryWrapper<TCommentRecord> commentQueryWrapper = new LambdaQueryWrapper<>();
            commentQueryWrapper.ne(TCommentRecord::getIsOpen, 1);
            commentQueryWrapper.isNotNull(TCommentRecord::getNoticeTime);
            commentQueryWrapper.eq(TCommentRecord::getDelFlag, "0");
            String time = DateUtils.parseDateToStr(
                    DateUtils.YYYY_MM_DD_HH_MM, DateUtils.getNowDate());
            //commentQueryWrapper.apply("( DATE_FORMAT( notice_time, '%Y-%m-%d %H:%i') = '" + time + "')");
            commentQueryWrapper.apply("( notice_time  <= now() )");
            commentRecords = commentRecordMapper.selectList(commentQueryWrapper);
        }

        if (!CollectionUtils.isEmpty(tMemoRecords)) {
            for (TMemoRecord tMemoRecord : tMemoRecords) {
                Map<String, String> map = new HashMap<>();
                map.put("info", "客户信息：" + tMemoRecord.getCustomerName() + "【 " + tMemoRecord.getCustomerTel() + " 】" + "</br>"
                        + "备忘录提醒内容：" + tMemoRecord.getContent());
                List<String> userIds = new ArrayList<>();
                userIds.add(String.valueOf(tMemoRecord.getUserId()));
                // 异步去执行
                sentInfo(Constants.MESSAGE_MEMO_RECORD, JSONObject.toJSONString(map), userIds, "备忘录提醒");
                tMemoRecord.setIsOpen(1);
                memoRecordMapper.updateById(tMemoRecord);
            }
        }

        if (!CollectionUtils.isEmpty(commentRecords)) {
            for (TCommentRecord commentRecord : commentRecords) {
                Map<String, String> map = new HashMap<>();
                map.put("info", "客户信息：" + commentRecord.getCustomerName() + "【 " + commentRecord.getCustomerTel() + " 】" + "</br>"
                        + "来自主管: 【" + commentRecord.getCreateBy() + "】的点评信息：" + commentRecord.getContent());
                List<String> userIds = new ArrayList<>();
                userIds.add(String.valueOf(commentRecord.getUserId()));
                // 异步去执行
                sentInfo(Constants.MESSAGE_COMMENT_RECORD, JSONObject.toJSONString(map), userIds, "主管点评");
                commentRecord.setIsOpen(1);
                commentRecordMapper.updateById(commentRecord);
            }
        }
    }

    /**
     * 发送消息
     */
    private void sentInfo(String type, String content, List<String> userIds, String operationName) {
        SentMessage send = new SentMessage();
        send.setType(type);
        send.setContent(content);
        send.setUserIds(userIds);
        send.setOperationName(operationName);
        SpringUtils.context().publishEvent(send);
    }

    /**
     * 晚上0点认领 新意向客户
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void claimCustomer() {
        customerService.newIntention();
    }
}
